package cn.jdemo.core.unload;

import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.concurrent.TimeUnit;

/**
 * 设置-XX:+TraceClassLoading -XX:+TraceClassUnloading
 *
 */
public class Demo {
    /**
     * 是有优化吗？并没有看到类卸载
     *
     * [Loaded java.lang.Void from D:\env\jdk8\jdk1.8.0_251\jre\lib\rt.jar]
     * loading...
     * [Loaded cn.jdemo.core.testcase.Test from file:/D:/gm/code/jdemo/jdemo/jdemo-core/target/classes/]
     * [Loaded java.lang.Shutdown from D:\env\jdk8\jdk1.8.0_251\jre\lib\rt.jar]
     * [Loaded java.lang.Shutdown$Lock from D:\env\jdk8\jdk1.8.0_251\jre\lib\rt.jar]
     */
    public static void main(String[] args) throws InterruptedException {
        // 等待两秒，让系统加载完所有的类
        Thread.sleep(2000);
        try {
            System.out.println("loading...");
            // 利用反射，加载ComplexClass类
            URLClassLoader loader = new URLClassLoader(new URL[]{new URL("file:/D:/gm/code/jdemo/jdemo/jdemo-core/src/main/java/cn/jdemo/core/testcase")});
            Class<?> aClass = loader.loadClass("cn.jdemo.core.testcase.Test");
            // 将加载这个类的URLClassLoader的引用置为null，以便让这个类释放
            loader = null;
            aClass = null;
            System.gc();
            TimeUnit.MILLISECONDS.sleep(2000);
        } catch (MalformedURLException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
